<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="供应商名称" prop="sno" style="width: 250px">
        <el-select
          v-model="queryParams.sno"
          placeholder="请选择供应商"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="[sno, name] in Array.from(supplierMap)"
            :key="sno"
            :label="name"
            :value="sno"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="零件名称" prop="pno" style="width: 250px">
        <el-select
          v-model="queryParams.pno"
          placeholder="请选择零件"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="[pno, pname] in Array.from(partMap)"
            :key="pno"
            :label="pname"
            :value="pno"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="项目工程名称" prop="jno" style="width: 250px">
        <el-select
          v-model="queryParams.jno"
          placeholder="请选择项目工程"
          clearable
          style="width: 100%"
        >
          <el-option
            v-for="[jno, jname] in Array.from(projectMap)"
            :key="jno"
            :label="jname"
            :value="jno"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['spm:spj:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['spm:spj:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['spm:spj:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['spm:spj:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="spjList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="供应商名称" align="center" prop="sno" />
      <el-table-column label="零件名称" align="center" prop="pno" />
      <el-table-column label="项目工程名称" align="center" prop="jno" />
      <el-table-column label="零件数量" align="center" prop="qty" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['spm:spj:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['spm:spj:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改供应关系数据管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="spjRef" :model="form" :rules="rules" label-width="80px">
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Spj">
import { listSpj, getSpj, delSpj, addSpj, updateSpj } from "@/api/spm/spj"
import { listPart} from "@/api/spm/part"
import { listSupplier} from "@/api/spm/supplier"
import { listProject} from "@/api/spm/project"
const { proxy } = getCurrentInstance()

const spjList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    sno: null,
    pno: null,
    jno: null,
  },
  rules: {
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询供应关系数据管理列表 */
function getList() {
  loading.value = true
  listSpj(queryParams.value).then(response => {
    response.rows.forEach(item => {
      item.pno = partMap.value.get(item.pno)
      item.sno = supplierMap.value.get(item.sno)
      item.jno = projectMap.value.get(item.jno)
    })
    spjList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    sno: null,
    pno: null,
    jno: null,
    qty: null
  }
  proxy.resetForm("spjRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.sno)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加供应关系数据管理"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _sno = row.sno || ids.value
  getSpj(_sno).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改供应关系数据管理"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["spjRef"].validate(valid => {
    if (valid) {
      if (form.value.sno != null) {
        updateSpj(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addSpj(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _snos = row.sno || ids.value
  proxy.$modal.confirm('是否确认删除供应关系数据管理编号为"' + _snos + '"的数据项？').then(function() {
    return delSpj(_snos)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('spm/spj/export', {
    ...queryParams.value
  }, `spj_${new Date().getTime()}.xlsx`)
}

const partMap = ref(new Map())
/** 查询零件数据 */
function getPartList() {
  return new Promise((resolve, reject) => {
    listPart(partQueryParams).then(response => { 
      response.rows.forEach(item => {  
        partMap.value.set(item.pno, item.pname)
      })
      resolve()
    }).catch(reject)
  })
}
const partQueryParams = {
    pageNum: 1,
    pageSize: 10000,
    pno: null,
    pname: null,
  }

const supplierMap = ref(new Map())
/** 查询供应商数据 */
function getSupplierList() {
  return new Promise((resolve, reject) => {
    listSupplier(supplierQueryParams).then(response => { 
      response.rows.forEach(item => {  
        supplierMap.value.set(item.sno, item.sname)
      })
      console.log(supplierMap.value);
      resolve()
    }).catch(reject)
  })
}
const supplierQueryParams = {
    pageNum: 1,
    pageSize: 10000,
    sno: null,
    sname: null,
  }

const projectMap = ref(new Map())
/** 查询项目工程数据 */
function getProjectList() {
  return new Promise((resolve, reject) => {
    listProject(projectQueryParams).then(response => { 
      response.rows.forEach(item => {  
        projectMap.value.set(item.jno, item.jname)
      })
      resolve()
    }).catch(reject)
  })
}
const projectQueryParams = {
    pageNum: 1,
    pageSize: 10000,
    jno: null,
    jname: null,
  }

onMounted(async () => {
  try {
    loading.value = true
    // 先加载所有基础数据
    await Promise.all([
      getPartList(),
      getSupplierList(),
      getProjectList()
    ])
    // 基础数据加载完成后，再加载列表
    await getList()
  } catch (error) {
    console.error('数据加载失败:', error)
    proxy.$modal.msgError("数据加载失败，请刷新页面重试")
  } finally {
    loading.value = false
  }
})
</script>
